import { cache } from "@/utils/cache"

import { decrypt, encrypt } from "@/utils/jsencrypt"

export type TokenType = {
  id: number // 编号
  accessToken: string // 访问令牌
  refreshToken: string // 刷新令牌
  userId: number // 用户编号
  userType: number //用户类型
  clientId: string //客户端编号
  expiresTime: number //过期时间
}

// ----------------------------- token相关 ----------------------------- //

const AccessTokenKey = "ACCESS_TOKEN"
const RefreshTokenKey = "REFRESH_TOKEN"

/**
 * 无感刷新token
 * @returns
 */
export const refreshTokenApi = async () => {
  try {
    // const result = await axios.post(`${base_url}/system/auth/refresh-token?refreshToken=${getRefreshToken()}`)
    // setToken(result.data)
  } catch (error) {
    throw new Error("无感刷新失败！")
  }
}

/**
 * 获取token
 * @returns {string}
 */
export const getAccessToken = () => {
  // 此处与TokenKey相同，此写法解决初始化时Cookies中不存在TokenKey报错
  return cache.getUser<string>(AccessTokenKey) ? cache.getUser(AccessTokenKey) : cache.getUser("ACCESS_TOKEN")
}

/**
 * 获取refreshToken
 * @returns {string}
 */
export const getRefreshToken = () => {
  return cache.getUser<string>(RefreshTokenKey)
}

/**
 * 设置token、refreshToken
 * @param token TokenType
 */
export const setToken = (token: TokenType) => {
  cache.setUser(AccessTokenKey, token.accessToken)
  cache.setUser(RefreshTokenKey, token.refreshToken)
}

/**
 * 删除token、refreshToken
 */
export const removeToken = () => {
  cache.removeUser(AccessTokenKey)
  cache.removeUser(RefreshTokenKey)
}

/**
 * 格式化token（jwt格式）
 * @param token
 * @returns {string}
 */
export const formatToken = (): string => `Bearer ${getAccessToken()}`

// ----------------------------- 账号登录相关 ----------------------------- //

const LoginFormKey = "LOGINFORM"

export type LoginFormType = {
  username: string
  password: string
  rememberMe: boolean
}

/**
 * 获取登录信息
 * @returns {LoginFormType}
 */
export const getLoginForm = () => {
  const loginForm = cache.getUser<LoginFormType>(LoginFormKey)
  if (loginForm) {
    loginForm.password = decrypt(loginForm.password) as string
  }
  return loginForm
}

/**
 * 设置登录信息
 * @param loginForm
 */
export const setLoginForm = (loginForm: LoginFormType) => {
  loginForm.password = encrypt(loginForm.password) || ""
  cache.setUser(LoginFormKey, loginForm, 30 * 24 * 60 * 60)
}

/**
 * 删除登录信息
 */
export const removeLoginForm = () => cache.removeUser(LoginFormKey)

// ----------------------------- SSO登录相关 ----------------------------- //
